<template>

    <div>
        <h1>我的网盘文件列表</h1>
        <div>
            <el-progress :stroke-width="26" :percentage="(capacity.currentCapacity/capacity.totalCapacity*100).toFixed(5)" :format="percentFormat"></el-progress>

        </div>
        <div>
            <div style="display: flex;">
                <el-upload
                        class="upload-demo"
                        action="http://localhost:10010/wangpanfile/wangpan-file/upload"
                        :show-file-list="false" :on-success="uploadSuccess"
                >
                    <el-button type="primary">点击上传</el-button>
                </el-upload>
                <el-button @click="toAddNewDir">新建文件夹</el-button>
                <el-button @click="goMyShareUrls">我的分享链接管理</el-button>
                <el-button @click="goBack" v-if="currentPid!=-1">返回上级</el-button>
                <el-button v-if="fileFlag" @click="toEdit">重命名</el-button>
                <el-button v-if="fileFlag" @click="downloadFile">下载</el-button>
                <el-button v-if="moveFlag" @click="toMoveFile">移动选中文件</el-button>
                <el-button v-if="delAllFlag" @click="toDelAll" type="danger">批量删除</el-button>
                <el-button v-if="shareFlag" @click="toShare" type="success">分享当前文件</el-button>
            </div>
            <!--table信息-->
            <div>
                <el-table
                        :data="tableData"  @selection-change="handleSelectionChange"
                        style="width: 100%">
                    <el-table-column
                            type="selection"
                            width="55">
                    </el-table-column>
                    <el-table-column
                            label="类型" width="80">
                        <template slot-scope="scope">
                            <img v-if="scope.row.type==2" src="../assets/file.png" style="width: 50px">
                            <img v-if="scope.row.type==1" src="../assets/dir.png" style="width: 50px">
                        </template>
                    </el-table-column>
                    <el-table-column
                            label="名称">
                        <template slot-scope="scope">
                            <el-button v-if="scope.row.type==1" type="text" @click="goNext(scope.row.id)">{{scope.row.name}}</el-button>
                            <el-button v-if="scope.row.type==2" type="text" @click="goDetail(scope.row.id)">{{scope.row.name}}</el-button>
                        </template>
                    </el-table-column>
                    <el-table-column
                            prop="createTime"
                            label="时间">
                    </el-table-column>
                    <el-table-column
                            label="大小">
                        <template slot-scope="scope">
                            {{getHumanSizeStr(scope.row.filesize)}}
                        </template>
                    </el-table-column>
                </el-table>

            </div>

        </div>



        <el-dialog title="重命名文件" :visible.sync="dialogFormVisible">
            <el-form :model="form">
                <el-form-item label="活动名称" :label-width="formLabelWidth">
                    <el-input v-model="form.name" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="updateFile">确 定</el-button>
            </div>
        </el-dialog>


        <el-dialog title="移动文件" :visible.sync="dialogFormVisibleMoveFlag">
            <el-button v-if="currentPidMove!=-1" @click="goBackMove">返回上一级</el-button>
            <div>
                <el-table
                        :data="toMovetableData"
                        style="width: 100%">
                    <el-table-column
                            label="名称">
                        <template slot-scope="scope">
                            <el-button type="text" @click="goNextMoveFile(scope.row.id)">{{scope.row.name}}</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="moveToDir">移动到此</el-button>
            </div>
        </el-dialog>


        <el-dialog title="新建文件夹" :visible.sync="dialogFormVisibleDir">
            <el-form :model="formDir">
                <el-form-item label="名称" :label-width="formLabelWidth">
                    <el-input v-model="formDir.name" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="addDir">确 定</el-button>
            </div>
        </el-dialog>



        <el-dialog title="分享文件" :visible.sync="dialogFormVisibleShare">
            <el-form :model="formShare">
                <el-form-item label="有效期" :label-width="formLabelWidth">
                    <el-radio v-model="formShare.days" label="7">7天</el-radio>
                    <el-radio v-model="formShare.days" label="15">15天</el-radio>
                    <el-radio v-model="formShare.days" label="30">30天</el-radio>
                </el-form-item>
                <el-form-item label="提取码" :label-width="formLabelWidth">
                    <el-input v-model="formShare.code"  maxlength="4">
                        <template slot="append" >
                            <el-button @click="geneCode" type="primary" >生成提取码</el-button>
                        </template>
                    </el-input>

                </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="shareFile">确 定</el-button>
            </div>
        </el-dialog>


        <el-dialog title="分享结果" :visible.sync="dialogFormVisibleShareResult">
            <div>

                <div>
                    分享链接：http://192.168.0.112:8888/share?sid={{formShare.id}}
                </div>
                <div>
                    提取码：{{formShare.code}}
                </div>
                <div>
                    {{formShare.days}}天之后过期
                </div>
                <div>
                    <el-button @click="copyContent">复制链接以及提取码</el-button>
                </div>

            </div>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="dialogFormVisibleShareResult=false">关闭</el-button>
            </div>
        </el-dialog>


    </div>

</template>

<script>
    export default {
        name: "my",
        data(){
            return {
                user:{},//当前登录人的信息
                tableData:[],
                capacity:{},
                currentPid:-1,//当前页面的pid
                pids:[-1],//存放所有的路径的pid
                multipleSelection:[],
                fileFlag:false,
                moveFlag:false,
                delAllFlag:false,
                shareFlag:false,

                dialogFormVisible: false,
                form: {
                    name: '',
                    id:"",
                    pid:"",
                },
                formLabelWidth: '120px',

                dialogFormVisibleMoveFlag:false,
                toMovetableData:[],
                currentPidMove:-1,
                pidsMove:[-1],

                dialogFormVisibleDir:false,
                formDir:{
                    name:"",
                    pid:"",
                    type:1,
                    filesize:0,
                    uid:"",
                },

                dialogFormVisibleShare:false,
                formShare:{
                    uid:"",
                    fid:"",
                    code:"",
                    state:"分享中",
                    days:"",
                },



                dialogFormVisibleShareResult:false,

            }
        },
        watch:{
            currentPid:{
                deep:true,
                handler(){
                    this.initWangpanListData();
                }
            },
            multipleSelection:{
                deep:true,
                handler(){
                    if(this.multipleSelection.length>0){
                        this.delAllFlag = true;
                        let flag = true;
                        for (let i = 0; i < this.multipleSelection.length; i++) {
                            let f = this.multipleSelection[i];
                            if(f.type==1){
                                flag = false;
                                break;
                            }
                        }



                        if(flag){
                            this.moveFlag = true;
                        }else{
                            this.moveFlag = false;
                        }
                        if(flag&&this.multipleSelection.length==1){
                            this.fileFlag = true;
                            this.shareFlag = true
                            return ;
                        }
                    }else{
                        this.delAllFlag = false;
                    }
                    this.fileFlag = false;
                    this.shareFlag = false


                }
            }
        },
        methods:{
            goMyShareUrls(){
                window.open("/myshare")
            },
            copyContent(){
                var input = document.createElement("textarea");   // js创建一个input输入框
                input.value = "http://192.168.0.112:8888/share?sid="+this.formShare.id+",提取码是："+this.formShare.code+"\n----来自网盘SVIP9用户的分享";  // 将需要复制的文本赋值到创建的input输入框中
                document.body.appendChild(input);    // 将输入框暂时创建到实例里面
                input.select();   // 选中输入框中的内容
                document.execCommand("Copy");   // 执行复制操作
                document.body.removeChild(input); // 最后删除实例中临时创建的input输入框，完成复制操作
                this.$message.success("复制成功")
            },
            shareFile(){
                this.formShare.uid = this.user.id;
                this.formShare.fid = this.multipleSelection[0].id
                this.axios.post(`/wangpanshare/share-info/shareFile`,this.formShare).then(res=>{
                    if(res.data.code==1){
                        this.formShare.id = res.data.data;

                        this.dialogFormVisibleShare = false;
                        this.dialogFormVisibleShareResult = true;

                    }else{
                        this.$message.error(res.data.message)
                    }
                })
            },
            toShare(){
                this.formShare = {
                    uid:"",
                    fid:"",
                    code:"",
                    state:"分享中",
                    days:"",
                }
                this.dialogFormVisibleShare = true;
            },
            geneCode(){
                let source = "abcdefghijklmnopqrstuvwxyz1234567890".split("");//[a,b,c]

                this.formShare.code = "";
                for (let i = 0; i < 4; i++) {
                    let index = (Math.random()*source.length).toFixed(0)
                    this.formShare.code+=source[index];
                }




            },
            toDelAll(){
                this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let ids = this.multipleSelection.map(f=>f.id).join(",")
                    this.axios.post(`/wangpanfile/wangpan-file/deleteBatch?ids=`+ids).then(res=>{
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                        this.initWangpanListData();
                    })

                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            addDir(){
                this.formDir.pid = this.currentPid;
                this.formDir.uid = this.user.id;

                this.axios.post(`/wangpanfile/wangpan-file/addDir`,this.formDir).then(res=>{
                    this.formDir = {
                        name:"",
                        pid:"",
                        type:1,
                        filesize:0,
                        uid:"",
                    }
                    this.dialogFormVisibleDir = false;
                    this.initWangpanListData();
                })
            },
            toAddNewDir(){
                this.dialogFormVisibleDir = true;

            },
            moveToDir(){
                let obj = {
                    fids:this.multipleSelection.map(f=>f.id).join(","),//1,2
                    toPid:this.currentPidMove
                }
                this.axios.post(`/wangpanfile/wangpan-file/moveFile?toPid=${obj.toPid}&fids=${obj.fids}`).then(res=>{
                    this.currentPidMove = -1;
                    this.pidsMove = [-1];
                    this.dialogFormVisibleMoveFlag = false
                    this.initWangpanListData();
                })

            },
            goBackMove(){
                this.pidsMove.splice(this.pidsMove.length-1);//移除最后一位，
                this.currentPidMove = this.pidsMove[this.pidsMove.length-1];//设置上一级的pid
                this.initWangpanListDataMove();
            },
            goNextMoveFile(id){
                this.currentPidMove = id;//设置当前页面的pid
                this.pidsMove.push(id);//存储到文件路径集合
                this.initWangpanListDataMove();
            },
            initWangpanListDataMove(){
                this.axios.post(`/wangpanfile/wangpan-file/findFileListByUid?type=1&uid=${this.user.id}&pid=${this.currentPidMove}`).then(res=>{
                    this.toMovetableData = res.data.data;
                })
            },
            toMoveFile(){
                this.initWangpanListDataMove();
                this.dialogFormVisibleMoveFlag = true
            },
            toEdit(){
                let f = this.multipleSelection[0]
                this.form.id = f.id;
                this.form.name = f.name;
                this.form.pid = f.pid;
                this.dialogFormVisible = true;
            },
            updateFile(){
                this.axios.post(`/wangpanfile/wangpan-file/update`,this.form).then(res=>{
                    if(res.data.code==1){
                        this.$message.success("修改成功")
                        this.form = {
                            name: '',
                            id:"",
                            pid:"",
                        }
                        this.dialogFormVisible = false;
                        this.initWangpanListData()
                    }else{
                        this.$message.error(res.data.message)
                    }

                })

            },
            downloadFile(){
                let url = "http://192.168.0.112:10010/wangpanfile/file/"+this.multipleSelection[0].url;
                window.open(url);
            },
            goDetail(id){
                window.open("/detail?id="+id)
            },
            goBack(){//【-1,2,3,4,5,6,7】
                this.pids.splice(this.pids.length-1);//移除最后一位，
                this.currentPid = this.pids[this.pids.length-1];//设置上一级的pid
            },
            goNext(id){
                this.currentPid = id;//设置当前页面的pid
                this.pids.push(id);//存储到文件路径集合
            },
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            percentFormat(value){
                let current = this.getHumanSizeStr(this.capacity.currentCapacity)
                let last = this.getHumanSizeStr(this.capacity.lastCapacity)
                let total = this.getHumanSizeStr(this.capacity.totalCapacity)
                return `用量：${current}；余量：${last}；总量：${total}；占比：${value}%；`;
            },
            getHumanSizeStr(size){
                let str = "";
                /**
                 * 1M以下，显示xxxKB
                 * 1M-1G之间，显示xxMB
                 * 1G-1T之间，显示xxGB
                 * 1T以上，显示XXTB
                 */

                let s = size/1024;//换算成KB
                if(s<1024){
                    str = s.toFixed(2) + "KB";
                    return str;
                }
                s = s/1024;//换算成MB
                if(s<1024){
                    str = s.toFixed(2) + "MB";
                    return str;
                }
                s = s/1024;//换算成GB
                if(s<1024){
                    str = s.toFixed(2) + "GB";
                    return str;
                }
                s = s/1024;//换算成TB
                if(s<1024){
                    str = s.toFixed(2) + "TB";
                    return str;
                }
            },
            uploadSuccess(res,file){

                let hashmap = res.data;

                let suffix = "未知";
                if(file.name.indexOf(".")>-1){
                    suffix = file.name.substring(file.name.lastIndexOf(".")+1);
                }

                let obj = {
                    name:file.name,
                    pid:this.currentPid,
                    type:2,
                    suffix,
                    md5str:hashmap.md5,
                    filesize:file.size,
                    url:hashmap.url,
                    uid:this.user.id
                }

                this.axios.post("/wangpanfile/wangpan-file/add",obj).then(res=>{
                    this.$message.success("上传成功");
                    this.initWangpanListData();
                    this.initCapacityData();
                })

            },
            initWangpanListData(){
                this.axios.post(`/wangpanfile/wangpan-file/findFileListByUid?uid=${this.user.id}&pid=${this.currentPid}`).then(res=>{
                    this.tableData = res.data.data;
                })
            },
            initCapacityData(){
                this.axios.post("/wangpancapacity/capacity/findByUid?uid="+this.user.id).then(res=>{
                    this.capacity = res.data.data;
                })

            }

        },
        created(){

            let user = localStorage.getItem("wangpan_user");
            if(!user){
                this.$message.error("请先去登录")
                setTimeout(()=>{
                    this.$router.push("/")
                },1500)
            }else{
                this.user = JSON.parse(user);
                this.initWangpanListData();
                this.initCapacityData();
            }
        }
    }
</script>

<style scoped>

</style>
